package zcw.com.lib_leet_code;

import java.util.Deque;
import java.util.LinkedList;

/**
 * Created by 朱城委 on 2021/9/9.<br><br>
 *
 * 中等：简化路径
 */
public class Topic71 {

    public static void main(String[] args) {
        Topic71 instance = new Topic71();

        System.out.println(instance.simplifyPath("/home/"));
        System.out.println(instance.simplifyPath("/../"));
        System.out.println(instance.simplifyPath("/home//foo/"));
        System.out.println(instance.simplifyPath("/a/./b/../../c/"));
    }

    public String simplifyPath(String path) {
        Deque<String> deque = new LinkedList<>();

        String[] array = path.split("/");

        for(String str : array) {
            if(str.equals(".") || str.equals("")) {
                continue;
            }
            else if(str.equals("..")) {
                deque.pollLast();
            }
            else {
                deque.offer(str);
            }
        }

        StringBuilder builder = new StringBuilder("/");
        while (!deque.isEmpty()) {
            builder.append(deque.poll());

            if(!deque.isEmpty()) {
                builder.append("/");
            }
        }
        return builder.toString();
    }
}
